<template>
  <page-header-wrapper @back="onBack">
    <template v-slot:extra>
      <a-upload list-type="text" accept=".xls,.xlsx" :showUploadList="false" :before-upload="imp">
        <a-button type="primary"> <a-icon type="form" /> 导入 </a-button>
      </a-upload>
    </template>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-form @submit="handleSubmit" :form="form">
        <a-divider>文档信息</a-divider>
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :sm="24">
            <a-upload name="avatar" :multiple="false" :before-upload="imageUpdate" :remove="imageRemove"
                      :fileList="imgList" accept=".jpg,.bmp,.png,.gif" list-type="picture">
              <a-button> <a-icon type="upload" /> 上传图片 </a-button>
            </a-upload>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-upload name="resume" :multiple="false" :before-upload="resumeUpdate" :remove="resumeRemove"
                      :fileList="resList">
              <a-button> <a-icon type="upload" /> 上传简历 </a-button>
            </a-upload>
          </a-col>
        </a-row>
        <a-divider>基础信息</a-divider>
        <a-row :gutter="16">
          <a-col v-for="(item, index) in items" :key="index" :lg="item.lg || 6" :md="item.md || 12" :sm="24">
            <a-form-item :label="item.label">
              <a-select v-if="item.options" :placeholder="item.label"
                        v-decorator="[item.key, {rules: []}]">
                <a-select-option v-for="(option, idx) in item.options" :key="idx"
                                 :value="option.id">{{option.name}}</a-select-option>
              </a-select>
              <a-date-picker v-else-if="item.type === 1" :placeholder="item.label" class="full-item"
                             v-decorator="[item.key, {rules: []}]"/>
              <a-input v-else :placeholder="item.label"
                      v-decorator="[item.key, {rules: []}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider>学习简历</a-divider>
        <a-row v-for="(item, index) in ['本科', '硕士', '博士']" :key="'s' + index" :gutter="16">
          <a-col :lg="6" :sm="24">
            <a-form-item :label="item + '起止时间'">
              <a-range-picker v-model="ext.study[index].time" class="full-item"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :sm="24">
            <a-form-item :label="item + '毕业学校'">
              <a-input v-model="ext.study[index].college" placeholder="毕业学校"/>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :sm="24">
            <a-form-item :label="item + '专业'">
              <a-input v-model="ext.study[index].major" placeholder="专业"/>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :sm="24">
            <a-form-item :label="item + '研究方向'">
              <a-input v-model="ext.study[index].research" placeholder="研究方向"/>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :sm="24">
            <a-form-item :label="item + '学制'">
              <a-input v-model="ext.study[index].system" placeholder="学制"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider>补充信息</a-divider>
        <a-form-item v-for="(item, index) in extItems" :key="index" :label="item.label">
          <a-textarea :placeholder="item.label" :auto-size="{ minRows: 3, maxRows: 5 }" v-model="ext[item.key]"/>
        </a-form-item>
        <a-form-item
          :wrapperCol="{ span: 24 }"
          style="text-align: center"
        >
          <a-button htmlType="submit" type="primary" :loading="loading">提交</a-button>
          <a-button style="margin-left: 8px" @click="onBack">返回</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </page-header-wrapper>
</template>

<script>
  import API from '@/api'
  import moment from 'moment'
  import pick from 'lodash.pick'
  import Adapter from '@/utils/adapter'
export default {
  name: 'ResumeForm',
  data () {
    Adapter.ResumeItems.BaseItems[0].options = this.$route.params.positions || []
    return {
      loading: false,
      form: this.$form.createForm(this),
      items: Adapter.ResumeItems.BaseItems,
      extItems: Adapter.ResumeItems.ExtItems,
      ext: { study: [{}, {}, {}] },
      imgList: [],
      resList: []
    }
  },
  mounted() {
    if (this.$route.params.id) {
      API.Resume.Content({id: this.$route.params.id}).then((res) => {
        if (res) {
          if (res.data.photo) {
            let name = this.getFilename(res.data.photo)
            let url = '/' + res.data.photo
            this.imgList.push({uid: '-1', name, status: 'done', url, thumbUrl: url})
          }
          if (res.data.attachments) {
            let name = this.getFilename(res.data.attachments)
            let url = '/' + res.data.attachments
            this.resList.push({uid: '-2', name, status: 'done', url})
          }
          res.data.birth = moment(res.data.birth)
          res.data.graduationTime = moment(res.data.graduationTime)
          const f = []
          for (let v of this.items) f.push(v.key)
          this.form.setFieldsValue(pick(res.data, f))
          this.ext = JSON.parse(res.data.extJson)
          if (this.ext && this.ext.study) {
            for (let i = 0; i < this.ext.study.length; i++) {
              let v = this.ext.study[i];
              if (v.begin && v.end) v.time = [moment(v.begin), moment(v.end)]
            }
            for (let i = this.ext.study.length; i < 3; i++) {
              this.ext.study.push({})
            }
          }
          else this.ext.study = [{}, {}, {}]
        }
      })
    }
  },
  methods: {
    getFilename(f) {
      let i = f.lastIndexOf('/')
      return i >= 0 ? f.substring(i + 1) : f
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          const params = {... values}
          if (this.imgList.length > 0 && this.imgList[0].uuid) {
            params.photo = this.imgList[0].uuid
          }
          if (this.resList.length > 0 && this.resList[0].uuid) {
            params.attachments = this.resList[0].uuid
          }
          params.birth = params.birth.valueOf()
          params.graduationTime = params.graduationTime.valueOf()
          params.extJson = JSON.stringify(this.ext)
          let key = "Edit"
          if (this.$route.params.id) params.id = this.$route.params.id
          else key = "Add"
          API.Resume[key](params).then((res) => {
            if (res) {
              this.$notification.success({message: '提示', description: '提交成功'})
              this.$router.push({path: this.$route.params.back})
            }
          }).finally(() => this.loading = false)
        }
        else this.$notification.error({message: '提示', description: '请检查必填项'})
      })
    },
    onBack() {
      this.$router.push({path: this.$route.params.back})
    },
    imageRemove() {
      this.imgList.splice(0, this.imgList.length)
    },
    imageUpdate(file) {
      this.upload(file, 5 * 1024 * 1024, this.imgList, '无法上传大小超过5M的图片')
      return false
    },
    resumeRemove() {
      this.resList.splice(0, this.resList.length)
    },
    resumeUpdate(file) {
      this.upload(file, 30 * 1024 * 1024, this.resList, '无法上传大小超过30M的文件')
      return false
    },
    upload(file, sizeLimit, list, desc) {
      if (file.size > sizeLimit) {
        this.$notification.error({message: '提示', description: desc})
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      if (list.length > 0) list.splice(0, 1)
      list.push(file)
      file.status = 'uploading'
      API.File.Update(formData).then(resp => {
        if (resp) {
          file.status = 'done'
          file.uuid = resp.data + '/' + file.name
          file.url = file.thumbUrl = '/' + file.uuid
        }
        else file.status = 'error'
        if (list.length > 0) list.splice(0, 1)
        list.push(file)
      })
    },
    imp(file) {
      this.loading = true
      Adapter.ResumeImport(file, data => {
        if (data) {
          const f = []
          for (let v of this.items) f.push(v.key)
          this.form.setFieldsValue(pick(data, f))
          this.ext = data.ext
        }
        else this.$notification.error({message: '提示', description: '读取简历表格失败'})
        this.loading = false
      })
      return false
    }
  }
}
</script>
